package com.gomcarter.frameworks.base.common;

import com.yifeng.repo.base.utils.converter.DateHelper;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

/**
 * Created by daibing on 2022/10/8.
 */
public class CustomLocalDateTimeUtils extends CustomDateUtils {

    public static LocalTime fromString2LocalTime(String dateStr) {
        return Optional.ofNullable(dateStr)
                .filter(str -> !str.isEmpty())
                .map(str -> {
                    String text = CustomStringUtils.replaceEach(dateStr, new String[]{"/", "\n",}, new String[]{"-", "",});
                    DateTimeFormatter formatter = getFormatter(text);
                    return LocalTime.parse(text, formatter);
                })
                .orElse(null);
    }

    public static LocalDate fromString2LocalDate(String dateStr) {
        return Optional.ofNullable(dateStr)
                .filter(str -> !str.isEmpty())
                .map(str -> {
                    String text = CustomStringUtils.replaceEach(dateStr, new String[]{"/", "\n",}, new String[]{"-", "",});
                    DateTimeFormatter formatter = getFormatter(text);
                    return LocalDate.parse(text, formatter);
                })
                .orElse(null);
    }

    public static LocalDateTime fromString2LocalDateTime(String dateStr) {
        return Optional.ofNullable(dateStr)
                .filter(str -> !str.isEmpty())
                .map(str -> {
                    String text = CustomStringUtils.replaceEach(dateStr, new String[]{"/", "\n",}, new String[]{"-", "",});
                    DateTimeFormatter formatter = getFormatter(text);
                    return LocalDateTime.parse(text, formatter);
                })
                .orElse(null);
    }

    private static DateTimeFormatter getFormatter(String dateStr) {
        boolean containDate = CustomStringUtils.contains(dateStr, "-");
        boolean containTime = CustomStringUtils.contains(dateStr, ":");
        if (containDate && containTime) {
            return DateHelper.DATE_TIME_FORMATTER;
        }
        if (containDate) {
            return DateHelper.DATE_FORMATTER;
        }
        if (containTime) {
            return DateHelper.TIME_FORMATTER;
        }
        return DateHelper.DATE_TIME_FORMATTER;
    }

    public static void main(String[] args) {
        LocalDateTime localDateTime = fromString2LocalDateTime("1000000000-01-01 00:00:00");
        System.out.println("localDateTime: " + localDateTime);
    }
}
